package com.example.douyin.home;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.example.douyin.R;
import com.example.douyin.adapter.PinglunAdapter;
import com.example.douyin.adapter.VideoAdapter;
import com.example.douyin.databinding.FragmentHomeBinding;
import com.example.douyin.db.DBUtils;
import com.example.lib_base_mvvm.baseMVVM.BaseView.BaseFragmnet;
import com.example.lib_base_mvvm.entity.PinglunEntity;
import com.example.lib_base_mvvm.entity.ResultEntity;
import com.example.lib_base_mvvm.entity.VideoEntity;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMVideo;

import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends BaseFragmnet<FragmentHomeBinding,HomeViewModel> {
    List<VideoEntity.DataBean> videos = new ArrayList<>();
    VideoAdapter videoAdapter;

    List<PinglunEntity.DataBean> pingluns = new ArrayList<>();
    PinglunAdapter pinglunAdapter;
    EditText etPinglun;
    int page = 1;
    int size = 10;
    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public int bindLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public void initView() {
        videoAdapter = new VideoAdapter(videos);
        dataBinding.rv.setAdapter(videoAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        dataBinding.rv.setLayoutManager(linearLayoutManager);
        //优化点1：滑动时，能准确的定位到其中一个item上，而不是显示半个
        PagerSnapHelper helper = new PagerSnapHelper();
        helper.attachToRecyclerView(dataBinding.rv);
        //优化点2：滑动到对应的item时，能够自动播放
        dataBinding.rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int position = linearLayoutManager.findFirstVisibleItemPosition();
                StandardGSYVideoPlayer player = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(position, R.id.gsy);
                player.startPlayLogic();
            }
        });

        viewModel.video(page,size);
        //点击点赞图标----recyclerview的子控件的点击事件
        videoAdapter.addChildClickViewIds(R.id.iv_dianzan,R.id.iv_pinglun,R.id.iv_shoucang,R.id.cl_full,R.id.cl_zhibo,R.id.iv_add,R.id.iv_close,R.id.iv_send,R.id.iv_fenxiang);
        videoAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()){
                    case R.id.iv_dianzan:
                        //ToastUtils.showLong("点击了点赞按钮图标");
                        dianzan(position);
                        break;
                    case R.id.iv_pinglun:
                        //ToastUtils.showLong("点击了pinglun");
                        dataBinding.rv.setInterceptor(false);
                        openpinglun(position);
                        break;
                    case R.id.iv_shoucang:
                        //ToastUtils.showLong("shoucang");
                        shoucang(position);
                        break;
                    case R.id.cl_full:
                        quanping(position);
                        break;
                    case R.id.cl_zhibo:
                        zhibo(position);
                        break;
                    case R.id.iv_add:
                        guanzhu(position);
                        break;
                    case R.id.iv_close:
                        dataBinding.rv.setInterceptor(true);
                        closepinglun(position);
                        break;
                    case R.id.iv_send:
                        sendpinglun(position);
                        break;
                    case R.id.iv_fenxiang:
                        fenxiang(position);
                        break;
                }
            }
        });

    }

    private void zhibo(int position) {
        ARouter.getInstance().build("/app/ZhiboActivity").withSerializable("video",videos.get(position)).navigation();
    }

    private void shoucang(int position) {
        DBUtils.getInstance().getVideoDao().insertVideo(videos.get(position));
        ToastUtils.showLong("收藏成功");
        ImageView iv = (ImageView) videoAdapter.getViewByPosition(position,R.id.iv_shoucang);
        iv.setImageResource(R.drawable.ic_shoucangyellow);
    }

    private void fenxiang(int position) {
        UMVideo video =new UMVideo(videos.get(position).getVideopath());
        video.setTitle(videos.get(position).getCaption());//视频的标题
        video.setThumb(new UMImage(getActivity(),videos.get(position).getVideomainimg()));//视频的缩略图
        video.setDescription(videos.get(position).getCaption());//视频的描述
        new ShareAction(getActivity()).withMedia(video).open();
    }

    private void quanping(int position) {
        StandardGSYVideoPlayer player = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(position, R.id.gsy);
        player.startWindowFullscreen(getContext(),true,true);
    }

    private void sendpinglun(int position) {
        int videoId = videos.get(position).getId();
        etPinglun = (EditText) videoAdapter.getViewByPosition(position, R.id.et_pinglun);
        String msg = etPinglun.getText().toString();
        viewModel.sendpinglun(videoId,msg);
    }

    private void closepinglun(int position) {
        //找到评论布局
        ConstraintLayout constraintLayout = (ConstraintLayout) videoAdapter.getViewByPosition(position, R.id.cl_pinglun);
        //隐藏评论布局
        constraintLayout.setVisibility(View.GONE);
        //添加一个动画效果--让约束布局从屏幕中缓慢下移 --补间动画
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.anmi_out);
        constraintLayout.startAnimation(animation);
    }

    private void openpinglun(int position) {
        //打开评论框--输入框自动获取焦点
        etPinglun = (EditText) videoAdapter.getViewByPosition(position, R.id.et_pinglun);
        etPinglun.requestFocus();//获取焦点，直接可以输入
        //找到评论布局
        ConstraintLayout constraintLayout = (ConstraintLayout) videoAdapter.getViewByPosition(position, R.id.cl_pinglun);
        //展示评论布局
        constraintLayout.setVisibility(View.VISIBLE);
        //添加一个动画效果--让约束布局从屏幕右侧缓慢弹出 --补间动画
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.anmi_in);
        animation.setInterpolator(new BounceInterpolator());//弹珠效果
        constraintLayout.startAnimation(animation);

        //显示评论内容  --先找到rv
        RecyclerView rvPinglun = (RecyclerView) videoAdapter.getViewByPosition(position, R.id.rv_pinglun);
        rvPinglun.setLayoutManager(new LinearLayoutManager(getContext()));
        pinglunAdapter = new PinglunAdapter(R.layout.item_pinglun,pingluns);
        rvPinglun.setAdapter(pinglunAdapter);

        viewModel.pinglun(videos.get(position).getId());//执行网络请求
        viewModel.pinglunSuccess.observe(this, new Observer<PinglunEntity>() {
            @Override
            public void onChanged(PinglunEntity entity) {
                if(entity.getCode()==200){
                    pingluns.clear();
                    pingluns.addAll(entity.getData());
                    pinglunAdapter.notifyDataSetChanged();
                }else{
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.pinglunFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });




    }

    private void guanzhu(int position) {
        //首先判断是否处于登录状态
        if(SPUtils.getInstance().getString("token").isEmpty()){
            ARouter.getInstance().build("/app/MainActivity").navigation();
        }else {
            viewModel.guanzhu(videos.get(position).getAuthname());
            ImageView iv = (ImageView) videoAdapter.getViewByPosition(position,R.id.iv_add);
            viewModel.guanzhuSuccess.observe(this, new Observer<ResultEntity>() {
                @Override
                public void onChanged(ResultEntity entity) {
                    if(entity.getCode()==200){
                        iv.setImageResource(R.drawable.ic_duigou);
                        //把对钩的背景色设为白色--自己优化
                        videos.get(position).setGuanzhu(1);
                        //添加动画效果
                        ObjectAnimator animator = ObjectAnimator.ofFloat(iv, "alpha", 1, 0);
                        animator.setDuration(2000);
                        animator.start();
                    }
                }
            });
        }
    }

    private void dianzan(int position) {
        //首先判断是否处于登录状态
        if(SPUtils.getInstance().getString("token").isEmpty()){
            ARouter.getInstance().build("/app/MainActivity").navigation();
        }else {
            //ToastUtils.showLong("点击了点赞按钮图标");
            //先判断一下当前处于什么状态
            int dianzan = videos.get(position).getDianzan();
            ImageView iv = (ImageView) videoAdapter.getViewByPosition(position, R.id.iv_dianzan);
            TextView tv = (TextView)  videoAdapter.getViewByPosition(position, R.id.tv_dianzan);
            if(dianzan==0){
                //执行点赞操作
                viewModel.love(videos.get(position).getId());//去执行网络请求
                viewModel.loveSuccess.observe(this, new Observer<ResultEntity>() {
                    @Override
                    public void onChanged(ResultEntity entity) {
                        if(entity.getCode()==200){
                            //让当前图片进行变更
                            iv.setImageResource(R.drawable.ic_xihuanred);
                            //修改实体类的值
                            videos.get(position).setDianzan(1);
                            tv.setText(videos.get(position).getLike_count()+1+"");
                            //添加动画效果
                            ObjectAnimator scaleX = ObjectAnimator.ofFloat(iv, "scaleX", 1, 2, 1);
                            ObjectAnimator scaleY = ObjectAnimator.ofFloat(iv, "scaleY", 1, 2, 1);
                            AnimatorSet set = new AnimatorSet();
                            set.play(scaleX).with(scaleY);
                            set.setDuration(2000);
                            set.start();

                        }
                    }
                });

            }else{
                //执行取消点赞的操作
                viewModel.nolove(videos.get(position).getId());
                viewModel.noloveSuccess.observe(this, new Observer<ResultEntity>() {
                    @Override
                    public void onChanged(ResultEntity entity) {
                        if(entity.getCode()==200){
                            //让当前图片进行变更
                            iv.setImageResource(R.drawable.ic_xihuan);
                            //修改实体类的值
                            videos.get(position).setDianzan(0);
                            tv.setText(videos.get(position).getLike_count()+"");
                        }
                    }
                });
            }
        }

    }

    @Override
    public void initData() {

        viewModel.videoSuccess.observe(this, new Observer<VideoEntity>() {
            @Override
            public void onChanged(VideoEntity entity) {
                if(entity.getCode()==200){
                    videos.addAll(entity.getData());
                    videoAdapter.notifyDataSetChanged();
                }else{
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.videoFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.sendpinglunSuccess.observe(this, new Observer<PinglunEntity>() {
            @Override
            public void onChanged(PinglunEntity entity) {
                if(entity.getCode()==200){
                    //显示在界面--显示在第一行
                    pingluns.add(0,entity.getData().get(0));
                    pinglunAdapter.notifyDataSetChanged();
                    etPinglun.setText("");
                }else{
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.sendpinglunFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });

    }

    @Override
    public Class<HomeViewModel> getViewModel() {
        return HomeViewModel.class;
    }
}